package 尊享面试.数组_字符串;

import java.util.Arrays;

public class a280摆动排序 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 2, 3};
        solution.wiggleSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    static class Solution {
        public void wiggleSort0(int[] nums) {
            // 1 2 3 4 5 6
            // 1 6 2 5 3 4
            int len = nums.length;
            int[] temp = new int[len];
            for (int i = 0; i < len; i++) {
                temp[i] = nums[i];
            }
            Arrays.sort(temp);
            int i = 0;
            int j = len - 1;
            int cnt = 0;
            boolean flag = true;
            while (cnt < len) {
                if (flag && i < len) {
                    nums[cnt++] = temp[i++];
                }
                if (!flag && j >= 0) {
                    nums[cnt++] = temp[j--];
                }
                flag = !flag;
            }
        }

        public void wiggleSort1(int[] nums) {
            Arrays.sort(nums);
            for (int i = 1; i < nums.length; i += 2) {
                swap(nums, i, i + 1);
            }
        }

        public void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[i + 1];
            nums[i + 1] = temp;
        }

        public void wiggleSort(int[] nums) {
            for (int i = 0; i < nums.length - 1; i++) {
                if (i % 2 == 0 && nums[i] > nums[i + 1]) {
                    swap(nums, i, i + 1);
                }
                if (i % 2 == 1 && nums[i] < nums[i + 1]) {
                    swap(nums, i, i + 1);
                }
            }
        }
    }
}
